#!/usr/bin/env python3
"""
CM5 / 树莓派 5 体检脚本
一键输出硬件型号、位数、温度、频率、内存、内核、USB/PCI 设备等关键信息
"""
import subprocess, pathlib, re, psutil

def sh(cmd):
    return subprocess.check_output(cmd, shell=True, text=True).strip()

def header(txt):
    print(f"\n========== {txt} ==========")

header("Hardware Model")
model = pathlib.Path("/proc/device-tree/model").read_text().rstrip("\0")
print(model)

header("64-bit OS ?")
print("getconf LONG_BIT =", sh("getconf LONG_BIT"))

header("Kernel / OS")
print(sh("uname -a"))
print("PRETTY_NAME =", sh("cat /etc/os-release | grep PRETTY_NAME"))

header("SoC 温度")
try:
    temp = sh("vcgencmd measure_temp").replace("temp=", "")
except Exception:
    temp = "❌ 无法读取（非树莓派官方内核？）"
print("CPU 温度:", temp)

header("CPU 频率")
core = 0
while True:
    f = pathlib.Path(f"/sys/devices/system/cpu/cpu{core}/cpufreq/scaling_cur_freq")
    if not f.exists():
        break
    MHz = int(f.read_text()) // 1000
    print(f"  core{core}: {MHz} MHz")
    core += 1

header("内存")
mem = psutil.virtual_memory()
print(f"总内存: {mem.total // 1024**3} GB   可用: {mem.available // 1024**3} GB")

header("USB 设备")
print(sh("lsusb"))

header("PCI 设备")
print(sh("lspci") if pathlib.Path("/usr/bin/lspci").exists() else "lspci 未安装（可 sudo apt install pciutils）")

header("串口枚举")
print(sh("ls /dev/ttyAMA* /dev/ttyUSB* 2>/dev/null || echo 无可见串口"))

if __name__ == "__main__":
    print("==== 树莓派 5 / CM5 体检结束 ====")